<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import echarts from '@/utils/echarts'
import { BarChartService } from '@/apis/home'

// 存储柱形图数据
const BarChartData = ref([])

// 获取柱形图数据
const getBarChart = async () => {
  const res = await BarChartService()
  BarChartData.value = res.data.data
}
// 获取图表容器
const chartContainerRef = ref(null)

// 声明一个变量用于保存echarts实例
let chartInstance = null

onMounted(async () => {
  // 调用函数获取柱形图数据
  await getBarChart()

  if (BarChartData.value.length > 0) {
    // 初始化图表
    chartInstance = echarts.init(chartContainerRef.value)

    // 定义图表的配置项和数据
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: BarChartData.value.map((item) => item.type),
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '房源类型',
          type: 'bar',
          itemStyle: {
            color: '#26c943'
          },
          barWidth: '60%',
          data: BarChartData.value.map((item) => item.count)
        }
      ]
    }

    // 使用配置项和数据显示图表格
    chartInstance.setOption(option)

    // 监听窗口大小变化，自动调整图表大小
    window.addEventListener('resize', () => {
      chartInstance.resize()
    })
  }
})

// 在组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    window.removeEventListener('resize', chartInstance.resize)
  }
})
</script>

<template>
  <div ref="chartContainerRef" class="chart"></div>
</template>

<style lang="scss" scoped>
.chart {
  width: auto;
  height: 400px;
}
</style>
